// @File  : user.go
// @Author: JunLong.Liao&此处不应有BUG!
// @Date  : 2021/5/21
// @slogan: 又是不想写代码的一天，神兽保佑，代码无BUG！
//         ┏┓      ┏┓
//        ┏┛┻━━━━━━┛┻┓
//        ┃     ღ    ┃
//        ┃  ┳┛   ┗┳ ┃
//        ┃     ┻    ┃
//        ┗━┓      ┏━┛
//          ┃      ┗━━━┓
//          ┃ 神兽咆哮!  ┣┓
//          ┃         ┏┛
//          ┗┓┓┏━━━┳┓┏┛
//           ┃┫┫   ┃┫┫
//           ┗┻┛   ┗┻┛

package user

import (
	"courseware/model"
	"courseware/util"
	"courseware/util/DB"
	"courseware/util/config"
	jwt "courseware/util/middleware/JWT"
	"courseware/util/rabbitmq_v2"
	"crypto/md5"
	"fmt"
	jwtgo "github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username") // post请求获取参数方法
	password := c.PostForm("password")
	if len(username) == 0 {
		util.ErrorResponse(c, "用户名不能为空", 1)
		return
	}
	if len(password) == 0 {
		util.ErrorResponse(c, "密码不能为空", 1)
		return
	}
	user := model.TUser{
		Username: username,
	}
	if err := user.GetUserByUsername(DB.DB); err != nil {
		util.ErrorResponse(c, "用户不存在", 1)
		return
	}

	data := []byte(password)
	has := md5.Sum(data)
	NewPassword := fmt.Sprintf("%x", has) // 将[]byte转成16进制
	fmt.Println(NewPassword)

	if NewPassword != user.Password {
		util.ErrorResponse(c, "密码不正确", 1)
		return
	}
	exp := config.Conf.Get("jwt", "exp")
	expire, _ := strconv.Atoi(exp)
	Times := time.Now().Unix()
	claims := jwt.CustomClaims{
		Id:       1,
		Username: username,
		StandardClaims: jwtgo.StandardClaims{
			NotBefore: Times,                       // 签名生效时间
			ExpiresAt: Times + int64(86400*expire), // 过期时间 一小时
			Issuer:    "now_im",                    // 签名的发行者
		},
	}
	token, _ := jwt.GenerateToken(c, &claims)

	res := LoginResponse{
		Username: username,
		Token:    token,
	}
	util.SuccessResponse(c, "data", res)
}

type LoginResponse struct {
	Username string `json:"username"`
	Token    string `json:"token"`
}

func Test(c *gin.Context) {
	claims, ok := c.Get("claims")
	if !ok {
		util.ErrorResponse(c, "获取token信息错误", 1)
	}
	testData := claims.(*jwt.CustomClaims)
	fmt.Printf("user_id:%s,username:%s\n", testData.Id, testData.Username)
}

func Register(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if len(username) == 0 {
		util.ErrorResponse(c, "用户名不能为空", 1)
		return
	}
	if len(password) == 0 {
		util.ErrorResponse(c, "密码不能为空", 1)
		return
	}

	data := []byte(password)
	has := md5.Sum(data)
	NewPassword := fmt.Sprintf("%x", has) // 将[]byte转成16进制
	fmt.Println(NewPassword)

	user := model.TUser{
		Username:    username,
		Password:    NewPassword,
		CreatedTime: time.Now().Unix(),
	}

	if err := user.CreateUer(DB.DB); err != nil {
		util.ErrorResponse(c, "新增失败", 1)
		return
	}
	util.SuccessResponse(c)
	return
}

func UpdateUser(c *gin.Context) {
	Id := c.PostForm("id")
	username := c.PostForm("username")
	if len(Id) == 0 {
		util.ErrorResponse(c, "ID不能为空", 1)
		return
	}
	if len(username) == 0 {
		util.ErrorResponse(c, "用户名不能为空", 1)
		return
	}
	// newId, _ := strconv.Atoi(Id)
	user := model.TUser{
		// ID:       int64(newId),
		Username: username,
	}
	if err := user.UpdateUser(DB.DB, Id); err != nil {
		util.ErrorResponse(c, "用户修改失败", 1)
		return
	}

	util.SuccessResponse(c)
	return
}

func DeleteUser(c *gin.Context) {
	Id := c.Query("id")
	if len(Id) == 0 {
		util.ErrorResponse(c, "ID不能为空", 1)
		return
	}
	// newId, _ := strconv.Atoi(Id)
	user := model.TUser{
		// ID:       int64(newId),
	}
	if err := user.DeleteUser(DB.DB, Id); err != nil {
		util.ErrorResponse(c, "用户修改失败", 1)
		return
	}

	util.SuccessResponse(c)
	return
}

func UserList(c *gin.Context) {

	user := new(model.TUser)
	list, err := user.GetUserList(DB.DB)
	if err != nil {
		util.SuccessResponse(c, "list", nil)
		return
	}

	util.SuccessResponse(c, "list", list)
	return
}

func RedisTest(c *gin.Context) {

	reply := DB.Redis.HSet("key2", "field", "value")

	reply2 := DB.Redis.HGet("key2", "field")
	fmt.Printf("reply:%s,reply2:%s\n", reply, reply2)
}

func RabbitMQ(c *gin.Context) {

	queueExchange := rabbitmq_v2.QueueExchange{
		"test_queue",
		"#.",
		"test",
		"topic",
		fmt.Sprintf("amqp://%s:%s@%s:%d/", "root", "123123", "127.0.0.1", 5672),
	}
	mq := rabbitmq_v2.NewMq(queueExchange)
	mq.MqConnect()
	for i := 0; i < 5; i++ {
		// t := &TestPro{
		// 	msgContent: fmt.Sprintf("{\"msg\":\"这是一条测试消息%v\"}", i),
		// }
		rabbitmq_v2.Send(queueExchange, fmt.Sprintf("{\"msg\":\"这是一条测试消息%v\"}", i))
	}

	t := &TestPro{}
	rabbitmq_v2.Recv(queueExchange, t, 1)
}

type TestPro struct {
	msgContent string
}

// 实现发送者
func (t *TestPro) FailAction(dataByte []byte) error {
	fmt.Println(string(dataByte))
	return nil
}

// 实现接收者
func (t *TestPro) Consumer(dataByte []byte) error {
	fmt.Printf("consumer:%s\n", string(dataByte))
	return nil
}
